/**
 * Created by xiniu on 2017/8/30.
 *待关闭中的重新解决
/**
 * Created by xiniu on 2017/8/30.
 */

import React, {Component, PropTypes} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    TextInput,
    Dimensions,
    TouchableOpacity,
    ScrollView,
    NativeModules,
    Platform,
} from 'react-native';

import Toast from 'react-native-simple-toast';
import AppService from '../service/AppService';
import RString from '../language/RString';

import MySuggestList from './MySuggestList';
import CoordinationList from './CoordinationList';
import agreeClose from './agreeClose';

export default class resolve extends Component {
    // 初始化
    constructor(props) {
        super(props);
        this.state = {
            title: RString('resolve_suggest'),
            reopenDescription: '',
            suggest: '',
        };
    }

    componentWillMount() {
        NativeModules.security.getPassportId().then((result) => {
                AppService.getPassport({id: result}).then((data) => {
                    global.tenantId = data.passport.tenantId;
                    this.state.userName = data.passport.userName;
                });
            },
        ).catch((error) => {
            console.log(error);
        });
        const vm = {
            tenantId: global.tenantId,
            id: this.props.id,
        };
        const _this = this;
        AppService.getSuggest(vm).then((data) => {
            if (!!data.errors === true && !!data.errors.length > 0) {
                Toast.show(data.errors[0].message);
            } else {
                _this.setState({
                    suggest: data.suggest || {},
                });
            }
        });
    }

    goBack = () => {
        const {navigator} = this.props;
        if (navigator) {
            navigator.pop();
        }
    };
    doClose = () => {
        NativeModules.system.navTo('BACK');
    };
    doCancel = () => {
        const {navigator} = this.props;
        if (navigator) {
            navigator.push({
                name: 'agreeClose',
                component: agreeClose,
                params: {
                    id: this.props.id,
                },
            });
        }
    };
    ensureResolve = () => {
        const _this = this;
        if (this.state.reopenDescription === '') {
            Toast.show(RString('empty_solution'));
        } else {
            const vm = {
                businessId: this.props.id,
                businessType: 'DOCK',
                anonymous: false,
                userId: global.userId,
                // content: this.props.reopenDescription?global.userName + '重新解决该提案。'+'\n'+'上次重新解决理由为：'+this.props.reopenDescription+'。'+'\n'+'完成情况为：'+this.props.dealMethod+'。':global.userName + '重新解决该提案。'+'\n'+'完成情况为：'+this.props.dealMethod+'。'
                content: `${global.userName + RString('call_resolve')}\n${RString('resolve_reason')}${RString('is')}${this.state.reopenDescription}。`,
            };

            // 创建重新解决的评论
            AppService.createCommentRecord(vm).then((data) => {
                if (!!data.errors === true && !!data.errors.length > 0) {
                    Toast.show(data.errors[0].message);
                } else {
                    // 创建完成情况的评论
                    AppService.createCommentRecord({
                        businessId: this.props.id,
                        businessType: 'DOCK',
                        anonymous: false,
                        userId: this.state.suggest.dealId,
                        content: `${this.state.suggest.dealName + RString('handle_proposal')}\n${RString('complete')}${RString('is')}${this.props.dealMethod}。`,
                    }).then((data) => {
                        if (!!data.errors === true && !!data.errors.length > 0) {
                            Toast.show(data.errors[0].message);
                        } else {
                            AppService.updateAttachmentBusiness({
                                businessId: data.id,
                                ids: global.completeUploadIdList
                            }).then((res) => {
                                if (!!res.errors === true && !!res.errors.length > 0) {
                                    Toast.show(res.errors[0].message);
                                } else {
                                    const {navigator} = _this.props;
                                    _this.state.suggest.reopenDescription = _this.state.reopenDescription;
                                    AppService.updateReopen({
                                        id: _this.state.suggest.id,
                                        reopenDescription: _this.state.suggest.reopenDescription,
                                        rowVersion: _this.state.suggest.rowVersion
                                    }).then((response) => {
                                        if (!!response.errors === true && !!response.errors.length > 0) {
                                            Toast.show(response.errors[0].message);
                                        } else {
                                            Toast.show(RString('resolve_success'));
                                            if (navigator) {
                                                if (global.isCoordinator) {
                                                    navigator.push({
                                                        name: 'CoordinationList',
                                                        component: CoordinationList,
                                                    });
                                                } else {
                                                    navigator.push({
                                                        name: 'MySuggestList',
                                                        component: MySuggestList,
                                                    });
                                                }
                                            }
                                        }
                                    });
                                }
                            });
                        }
                    });
                }
            });
        }
    };

    render() {
        return (
            <View style={{position: 'relative', flex: 1}}>
                <View style={styles.commonHeader}>
                    <TouchableOpacity onPress={this.goBack.bind(this)} style={styles.back}>
                        <Image source={require('./img/leftArrow.png')}/>
                    </TouchableOpacity>
                    <TouchableOpacity onPress={this.doClose.bind(this)} style={styles.toIndex}>
                        <Image source={require('./img/chahao.png')}/>
                    </TouchableOpacity>
                    <View style={{justifyContent: 'center'}}>
                        <Text style={{color: '#fff', fontSize: 16}}>{this.state.title}</Text>
                    </View>
                </View>
                <ScrollView style={styles.wrap}>
                    <View style={{flex: 1, paddingLeft: 15, paddingRight: 15, paddingTop: 10}}>
                        <TextInput
                            style={{flex: 1}}
                            placeholder={RString('fill_resolve')}
                            placeholderTextColor="#A9A9A9"
                            underlineColorAndroid="transparent"
                            multiline
                            numberOfLines={10}
                            textAlignVertical="top"
                            onChangeText={text => this.setState({reopenDescription: text})}
                        />
                    </View>
                </ScrollView>
                <View style={styles.buttonWrap}>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-start'}}>
                        <TouchableOpacity style={styles.editBtn} onPress={this.doCancel.bind(this)}>
                            <Text style={{color: '#424242'}}>{RString('cancel')}</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{flex: 1, flexDirection: 'row', justifyContent: 'flex-end'}}>
                        <TouchableOpacity style={styles.distributeBtn} onPress={this.ensureResolve.bind(this)}>
                            <Text style={{color: '#fff'}}>{RString('ensure')}</Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    wrap: {
        backgroundColor: '#fff',
    },
    commonHeader: {
        height: Platform.OS === 'android' ? 50 : 60,
        paddingTop: Platform.OS === 'ios' ? 20 : 0,
        backgroundColor: '#333238',
        flexDirection: 'row',
        justifyContent: 'center',
        position: 'relative',
    },
    back: {
        width: 30,
        position: 'absolute',
        left: 20,
        top: 0,
        height: Platform.OS === 'android' ? 50 : 60,
        paddingTop: Platform.OS === 'ios' ? 20 : 0,
        justifyContent: 'center',
    },
    toIndex: {
        width: 30,
        position: 'absolute',
        left: 70,
        top: 0,
        height: Platform.OS === 'android' ? 50 : 60,
        paddingTop: Platform.OS === 'ios' ? 20 : 0,
        justifyContent: 'center',
    },
    buttonWrap: {
        width: Dimensions.get('window').width,
        height: 55,
        backgroundColor: '#F5F5F5',
        paddingLeft: 20,
        paddingRight: 20,
        paddingTop: 10,
        paddingBottom: 10,
        flexDirection: 'row',
        position: 'absolute',
        bottom: 0,
        left: 0,
    },
    editBtn: {
        width: 100,
        borderWidth: 0.5,
        borderStyle: 'solid',
        borderColor: '#333',
        borderRadius: 5,
        paddingTop: 8,
        paddingBottom: 8,
        flexDirection: 'row',
        justifyContent: 'center',
    },
    distributeBtn: {
        width: 100,
        borderRadius: 5,
        paddingTop: 8,
        paddingBottom: 8,
        backgroundColor: '#3399FF',
        flexDirection: 'row',
        justifyContent: 'center',
    },
});

